from django.urls import reverse, re_path
from django.shortcuts import render
from django.utils.safestring import mark_safe
from django.http import QueryDict
from django.forms.models import modelformset_factory
from stark.service.s1 import StarkHandler
from app_main.forms.for_stark import TeachRecordModelForm, StudyRecordModelForm
from app_main import models


class TeachRecordHandler(StarkHandler):

    model_form_class = TeachRecordModelForm

    def display_edit(self, obj=None, is_head=None, *args, **kwargs):
        if is_head:
            return '编辑'

        cid = kwargs.get('cid')
        base_url = reverse('%s:%s' % (self.site.namespace, self.get_edit_url_name), kwargs={'cid': cid, 'nid': obj.id})
        if not self.request.GET:
            edit_url = base_url
        else:
            edit_url_dict = QueryDict(mutable=True)
            edit_url_dict['_addi'] = self.request.GET.urlencode()
            edit_url = '%s?%s' % (base_url, edit_url_dict.urlencode())

        return mark_safe("<a href='%s'>编辑</a>" % edit_url)

    def display_del(self, obj=None, is_head=None, *args, **kwargs):
        if is_head:
            return '删除'

        cid = kwargs.get('cid')
        base_url = reverse('%s:%s' % (self.site.namespace, self.get_delete_url_name), kwargs={'cid': cid, 'nid': obj.id})
        if not self.request.GET:
            del_url = base_url
        else:
            del_url_dict = QueryDict(mutable=True)
            del_url_dict['_addi'] = self.request.GET.urlencode()
            del_url = '%s?%s' % (base_url, del_url_dict.urlencode())

        return mark_safe("<a href='%s'>删除</a>" % del_url)

    def display_attendance(self, obj=None, is_head=None, *args, **kwargs):
        if is_head:
            return '考勤'

        re_url = reverse('stark:app_main_teachrecord_attendance', args=(obj.id,))
        return mark_safe('<a target="_blank" href="%s">考勤</a>' % re_url)

    list_display = [
        StarkHandler.display_checkbox,
        'day_num',
        'teacher',
        'date',
        display_attendance,
        display_edit,
        display_del
    ]

    def attendance_list(self, request, tid):
        study_record_list = models.StudyRecord.objects.filter(teach_record_id=tid)
        m_form_set = modelformset_factory(models.StudyRecord, form=StudyRecordModelForm, extra=0)
        my_m_form_set = m_form_set(queryset=study_record_list)

        if request.method == 'POST':
            p_m_form_set = m_form_set(queryset=study_record_list, data=request.POST)
            if p_m_form_set.is_valid():
                p_m_form_set.save()

            return render(request, 'app_main/attendance.html', {'m_form_set': p_m_form_set})
                
        return render(request, 'app_main/attendance.html', {'m_form_set': my_m_form_set})

    def get_urls(self):
        patterns = [
            re_path('list/(?P<cid>\d+)/$', self.wrapper(self.list_view), name=self.get_list_url_name),
            re_path('add/(?P<cid>\d+)/$', self.wrapper(self.add_view), name=self.get_add_url_name),
            re_path('edit/(?P<cid>\d+)/(?P<nid>\d+)/$', self.wrapper(self.edit_view), name=self.get_edit_url_name),
            re_path('delete/(?P<cid>\d+)/(?P<nid>\d+)/$', self.wrapper(self.delete_view), name=self.get_delete_url_name),
            re_path('attendance/(?P<tid>\d+)/$', self.wrapper(self.attendance_list), name=self.get_url_name('attendance'))
        ]

        patterns.extend(self.extra_urls())

        return patterns

    def get_query_set(self, request, *args, **kwargs):
        c_id = kwargs.get('cid')

        return self.model_class.objects.filter(to_class_id=c_id)

    def save(self, request, form_obj, is_update, *args, **kwargs):
        if not is_update:
            cid = kwargs.get('cid')
            form_obj.instance.to_class_id = cid

        form_obj.save()

    def multi_init(self, request, *args, **kwargs):  # 考勤记录初始化
        teach_id_list = request.POST.getlist('cb')
        c_id = kwargs.get('cid')
        c_obj = models.ClassList.objects.filter(id=c_id).first()  # 班级对象

        if not c_obj:
            return

        s_list = c_obj.student_set.all()  # 学生对象列表
        for teach_id in teach_id_list:
            t_obj = models.TeachRecord.objects.filter(id=teach_id, to_class_id=c_id).first()  # 上课记录对象
            # 判断该上课记录对象对应的考勤记录是否已经存在
            s_record_exist = models.StudyRecord.objects.filter(teach_record=t_obj).exists()

            if not s_record_exist:  # 如果不存在，创建考勤记录
                create_list = [models.StudyRecord(teach_record=t_obj, student=student) for student in s_list]
                models.StudyRecord.objects.bulk_create(create_list, batch_size=50)

    multi_init.text = '批量初始化考勤'

    action_list = [multi_init]
